package admin

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"encoding/json"
	"fmt"
	"github.com/go-xorm/xorm"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/kataras/iris/v12/sessions"
	"strings"
)

type LoginParams struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type AdminUserNoLogin struct {
	Ctx     iris.Context
}

// 初始化
func (c *AdminUserNoLogin) GetInit() interface{} {
	var ok bool
	var err error
	var db *xorm.Engine

	db, err = datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	sess := db.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据库事务开启失败：%s", err.Error()), "")
	}

	ok, _ = sess.ID(1).Exist(new(models.Role))
	if ok {
		return utils.CommonRes(1000, "已初始化", "")
	}

	ok, _ = sess.ID(1).Exist(new(models.Admin))
	if ok {
		return utils.CommonRes(1000, "已初始化", "")
	}

	ok, _ = sess.ID(1).Exist(new(models.SiteConfig))
	if ok {
		return utils.CommonRes(1000, "已初始化", "")
	}

	role := new(models.Role)
	role.Name = "超级管理员"
	role.Authorities = "admin"
	_, err = sess.InsertOne(role)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("初始化失败：%s", err.Error()), "")
	}

	account := "baokaobang"
	password := "baokaobang123!@"

	admin := new(models.Admin)
	admin.Name = "报考帮"
	admin.Avatar = "baokaobang.jpg"
	admin.Account = account
	admin.Password = utils.PasswordEncode(password)
	admin.RoleId = role.Id
	_, err = sess.InsertOne(admin)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("初始化失败：%s", err.Error()), "")
	}

	siteConfig := new(models.SiteConfig)
	siteConfig.IsTest = 0
	_, err = sess.InsertOne(siteConfig)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("初始化失败：%s", err.Error()), "")
	}

	sess.Commit()

	return utils.CommonRes(20000, fmt.Sprintf("成功初始化，管理员登录账号：%s，管理员登录密码：%s", account, password), "")
}

func (c *AdminUserNoLogin) OptionsLogin() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *AdminUserNoLogin) PostLogin() interface{} {
	loginParams := LoginParams{}
	content, err := c.Ctx.GetBody()
	session := sessions.Get(c.Ctx)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &loginParams)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if len(loginParams.Username) <= 0 {
		return utils.CommonRes(1000, "请输入管理员账号", "")
	}
	if len(loginParams.Password) < 6 {
		return utils.CommonRes(1000, "管理员密码至少6位", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	admin := new(models.Admin)
	ok, err := db.Where("account=?", loginParams.Username).Get(admin)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("登录异常:%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "不存在该管理员", "")
	}
	if !strings.EqualFold(admin.Password, utils.PasswordEncode(loginParams.Password)) {
		return utils.CommonRes(1000, "管理员密码不正确", "")
	}

	session.Set("adminUserId", admin.Id)
	session.Set("adminUniversityId", admin.UniversityId)
	sessionId := session.ID()

	return utils.CommonRes(20000, "登录成功", map[string]string{"token": sessionId})
}

func (c *AdminUserNoLogin) OptionsLogout() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *AdminUserNoLogin) PostLogout() interface{} {
	session := sessions.Get(c.Ctx)
	session.Destroy()
	return utils.CommonRes(20000, "已成功登出", "")
}
